<?php
namespace lib\sms;

class TencentSms
{
    private $appid;
    private $appkey;
    private $url;
    private $util;

    public function __construct($appid, $appkey)
    {
        $this->appid = $appid;
        $this->appkey = $appkey;
        $this->url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms";
        $this->util = new SmsSenderUtil();
    }

    public function send($type, $nationCode, $phoneNumber, $msg, $ext = "")
    {
        $random = $this->util->getRandom();
        $curTime = time();
        $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random;

        $data = [
            "tel" => [
                "nationcode" => "".$nationCode,
                "mobile" => "".$phoneNumber,
            ],
            "type" => (int) $type,
            "msg" => $msg,
            "sig" => hash("sha256", "appkey=".$this->appkey."&random=".$random."&time=".$curTime."&mobile=".$phoneNumber, FALSE),
            "time" => $curTime,
            "extend" => $ext,
            "ext" => ""
        ];

        return $this->util->sendCurlPost($wholeUrl, $data);
    }

    public function sendWithParam($nationCode, $phoneNumber, $templId = 0, $params, $sign = "", $ext = "")
    {
        $random = $this->util->getRandom();
        $curTime = time();
        $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random;

        $data = [
            "tel" => [
                "nationcode" => "".$nationCode,
                "mobile" => "".$phoneNumber,
            ],
            "sig" => $this->util->calculateSigForTempl($this->appkey, $random, $curTime, $phoneNumber),
            "tpl_id" => $templId,
            "params" => $params,
            "sign" => $sign,
            "time" => $curTime,
            "extend" => $ext,
            "ext" => ""
        ];

        return $this->util->sendCurlPost($wholeUrl, $data);
    }
}

class SmsSenderUtil
{
    public function getRandom()
    {
        return mt_rand(100000, 999999);
    }

    public function sendCurlPost($url, $data)
    {
        $jsonData = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($jsonData)
        ));

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    public function calculateSigForTempl($appkey, $random, $curTime, $phoneNumber)
    {
        return hash("sha256", "appkey=".$appkey."&random=".$random."&time=".$curTime."&mobile=".$phoneNumber, FALSE);
    }
}